<template>
  <el-container>
    <el-dialog
      :title="isAdd ? '班级添加' : '班级编辑'"
      :visible.sync="centerDialogVisible"
      @closed="closeDialog()"
      width="30%"
      center
    >
      <el-form
        ref="classroomForm"
        :model="classroomForm"
        label-width="100px"
        fullscreenLoading
        :rules="classroomFormRules"
      >
        <el-form-item label="班级名称" :prop="isAdd ? 'name' : 'editName'">
          <el-input
            v-model="classroomForm.name"
            placeholder="请输入班级名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="院系/专业" prop="depAndMajor">
          <el-cascader
            class="editCascader"
            placeholder="请选择院系/专业"
            v-model="classroomForm.departmentAndMajor"
            key="id"
            :options="depAndMajorMenu"
            :props="optionProps"
            clearable
            ref="departmentAndMajor"
            @change="cascaderChange"
          ></el-cascader>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="submitForm('classroomForm')"
            v-loading.fullscreen.lock="fullscreenLoading"
            >确认</el-button
          >
          <el-button @click="resetForm('classroomForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-container>
      <el-main>
        <el-row class="function-button">
          <el-button type="primary" size="small" round @click="handleAdd()"
            >新增按钮</el-button
          >
          <el-button type="success" size="small" round @click="refresh()"
            >刷新按钮</el-button
          >
          <el-input
            style="width: 20%; margin-left: 40px"
            placeholder="输入班级名"
            size="samll"
            prefix-icon="el-icon-search"
            v-model="classroomName"
          >
          </el-input>
          <el-cascader
            style="margin-left: 10px; width: 30%"
            placeholder="请选择院系/专业"
            v-model="depAndMajorMenu"
            key="id"
            :options="depAndMajorTree"
            :props="optionProps"
            clearable
            ref="departmentAndMajorTree"
          ></el-cascader>
          <el-button round style="margin-left: 10px" @click="queryByCondition"
            >查询</el-button
          >
        </el-row>
        <template>
          <el-table
            ref="classroomTable"
            :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }"
            v-loading="loading"
            :data="classrooms"
            fit
            max-height="700"
            size="medium "
            class="tableStyle"
            highlight-current-row
            row-key="id"
            tooltip-effect="dark"
          >
            <el-table-column prop="id" label="班级编号"> </el-table-column>
            <el-table-column prop="name" label="班级名称"> </el-table-column>
            <el-table-column prop="major" label="所属专业"> </el-table-column>
            <el-table-column prop="department" label="所属院系">
            </el-table-column>
            <el-table-column fixed="right" label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  @click.stop="handEdit(scope.row)"
                  size="small"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  @click.stop="handDel(scope.row)"
                  size="small"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </template>
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import throttle from 'lodash/throttle'; //
import { mapGetters } from 'vuex';
import { Message } from 'element-ui';
export default {
  name: 'ClassroomMng',
  data() {
    var validateNameIsRepeat = async (rule, value, callback) => {
      if (!value) {
        return callback([new Error('名称不能为空')]);
      }
      // 发送请求，判断名称是重复
      let result = await this.$store.dispatch(
        'AcademyMng/checkIsRepeatForClassroomName',
        value
      );
      return result.data.flag
        ? callback()
        : callback([new Error(result.message)]);
    };
    return {
      classrooms: [], // 展示班级列表
      total: 0,
      currentPage: 1,
      pageSize: 10,
      loading: false, // 遮罩层
      condition: {},
      isAdd: false, // 增加操作标志符
      depAndMajorMenu: [], // 院系/专业树
      fullscreenLoading: false,
      classroomForm: {}, // 表单对象
      centerDialogVisible: false, // 对话框开关
      classroomName: '', // 搜索框
      editClassroomForm: {}, // 编辑时对象
      optionProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        checkStrictly: true, // 来设置父子节点取消选中关联，从而达到选择任意一级选项的目的
      },
      classroomFormRules: {
        editName: [
          { required: true, validator: validateNameIsRepeat, trigger: 'blur' },
        ],
        name: [
          { required: true, validator: validateNameIsRepeat, trigger: 'blur' },
        ],
        // depAndMajor: [
        //   { required: true, message: '请选择院系/专业', trigger: 'change' },
        // ],
      },
    };
  },
  computed: {
    ...mapGetters('AcademyMng', [
      'classroomIPage',
      'classroomList',
      'depAndMajorTree',
    ]),
  },
  watch: {
    classroomIPage() {
      this.loading = false;
      this.$set(this, 'total', this.classroomIPage.total);
      this.currentPage = this.classroomIPage.currentPage;
      this.pageSize = this.classroomIPage.pageSize;
    },
    classroomList() {
      this.$set(this, 'classrooms', this.classroomList);
    },
    // depAndMajorTree() {
    //   this.$set(this, 'depAndMajorMenu', this.depAndMajorTree);
    // },
  },
  mounted() {
    this.getClassroomList();
    this.getDepaAndMajorTree();
  },
  methods: {
    // 删除班级
    handDel(row) {
      let result;
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
      })
        .then(async () => {
          result = await this.$store.dispatch('AcademyMng/delClassroom', [
            row.id,
          ]);
          this.$message({
            message: result.message,
            type: 'success',
            duration: 2 * 1000,
          });
          this.getClassroomList(this.depRowId);
        })
        .catch(() => {
          this.$message({
            message: result.message,
            type: 'success',
            duration: 2 * 1000,
          });
        });
    },
    // 对话框关闭前的回调
    closeDialog() {
      this.isAdd = false;
    },
    // 获取院系专业树
    getDepaAndMajorTree() {
      this.$store.dispatch('AcademyMng/getDepAndMajorMenu');
    },
    // 编辑班级
    handEdit(row) {
      let temp = {
        ...row,
      };
      this.classroomForm = temp;
      this.centerDialogVisible = true;
    },
    // 每页显示多少条
    handleSizeChange(val) {
      this.pageSize = val;
      this.getClassroomList();
    },
    // 当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getClassroomList();
    },
    // 条件查询
    async queryByCondition() {
      // 初始化条件查询参数
      this.condition = {};
      if (this.classroomName) {
        this.condition.name = this.classroomName;
      }
      if (this.depAndMajorMenu) {
        // 院系
        this.condition.departmentId = this.depAndMajorMenu[0];
        // 专业
        this.condition.majorId = this.depAndMajorMenu[1];
      }
      await this.getClassroomList();
      this.$nextTick(() => {
        this.$message({
          message: '查询成功',
          type: 'success',
          duration: 1 * 1000,
        });
      });
    },

    // 刷新班级列表
    refresh: throttle(async function () {
      this.currentPage = 1;
      await this.getClassroomList();
      this.$message({
        message: '刷新成功',
        type: 'success',
        duration: 1 * 1000,
      });
    }, 800),
    // 新增院系
    handleAdd() {
      this.classroomForm = {};
      this.isAdd = true;
      this.centerDialogVisible = true;
    },

    // 级联选择器
    cascaderChange() {
      // this.$refs["departmentAndMajor"].getCheckedNodes()//完整的数据
      //this.$refs["departmentAndMajor"].getCheckedNodes()[0].pathLabels//value的值
    },

    // 获取班级列表
    getClassroomList() {
      this.loading = true;
      let params = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        condition: this.condition,
      };
      this.$store.dispatch('AcademyMng/getClassroomList', params);
    },

    // 表单提交
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.fullscreenLoading = true;
          try {
            let result = {};
            // 将院系专业拆分出来
            let departmentId = this.classroomForm.departmentAndMajor[0];
            let majorId = this.classroomForm.departmentAndMajor[1];
            if (this.isAdd) {
              let paramsArray = [];
              // 发送请求
              let params = {
                ...this.classroomForm,
                departmentId,
                majorId,
              };
              paramsArray.push(params);
              result = await this.$store.dispatch(
                'AcademyMng/batchAddClassroom',
                paramsArray
              );
            } else {
              this.classroomForm.departmentId = departmentId;
              this.classroomForm.majorId = majorId;
              result = await this.$store.dispatch(
                'AcademyMng/editClassroom',
                this.classroomForm
              );
            }
            this.$message({
              message: result.message,
              type: 'success',
              duration: 2 * 1000,
            });
            // 更新班级列表
            this.getClassroomList();
          } catch (error) {
            Message.error(error || 'Has Error');
          } finally {
            this.fullscreenLoading = false;
            this.isAdd = false;
            this.centerDialogVisible = false;
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
// 级联框编辑样式
.editCascader {
  width: 100%;
}
.block {
  text-align: center;
}
</style>
